init = function(){}

var express = require('express')
  , app = require('express').createServer()
  , io = require('socket.io').listen(app)
  , db = require('http')
  , url = require('url')
  , mongo = require('./server/mongodb').create('127.0.0.1', 27017, 'test')
  , serviceRegistry = require('./ServiceRegistry')
  , remoteController = require('./server/RemotingController');

remoteController.set( 'mongo', mongo);
remoteController.set( 'room' , mongo.getDb('room'));
remoteController.set( 'user' , mongo.getDb('user'));
remoteController.set( 'item' , mongo.getDb('item'));
remoteController.set( 'alias' , mongo.getDb('alias'));

var bodyParser = function(req, options, callback){
	var _parser = require('connect').bodyParser();
	req.rawBody = '';
	req.on('data', function(chunk){
		req.rawBody += chunk;
	});
	_parser(req, options, callback);
}

app.use(bodyParser);
app.listen(8080);

app.get('/', function (req, res) {
  console.log('request for : /')	
  res.sendfile(__dirname + '/mud.html');
});
app.get('/:filename', function(req, res){
  console.log('request for : ' + req.params.filename);
  res.sendfile(__dirname + '/' + req.params.filename)
});
app.get('/client/:filename', function(req, res){
  console.log('request for : ' + req.params.filename);
  res.sendfile(__dirname + '/client/' + req.params.filename)
});
app.get('/ability/:filename', function(req, res){
  console.log('request for : ' + req.params.filename);
  res.sendfile(__dirname + '/ability/' + req.params.filename)
});
app.get('/thirdparty/*', function(req, res){
	var filename = url.parse(req.url).search;
	res.sendfile(__dirname + '/thirdparty/' + filename);
});

remoteController.register(app);

app.all('/db/*', function(req, res){
  var query = url.parse(req.url).search;
  var uri   = req.params + (query?query:'');
  
  console.log('[DB] ' + uri);
  var options = {
	host : 'localhost',
	port : 27080,
	path : uri,
	method : req.method
  };
  var onDbResponse = function(dbres){
	  dbres.on('data', function(chunk){
		 //console.log(chunk.toString());
		 res.write(chunk); 
	  });
	  dbres.on('end', function(){
		 //console.log('Done');
		 res.end(); 
	  });
  };
  
  var dbreqdata  = null;
  if( req.rawBody && (req.method == 'POST' || req.method == 'PUT') ){
	  dbreqdata = req.rawBody;
	  console.log(dbreqdata);
  }
  var dbreq = db.request(options, onDbResponse);
  dbreq.on('error', function(err){
	 console.log(err);
	 res.send(err, 500);
  });
  dbreq.on('continue', function(){
	  console.log('continue called');
  })
  if( dbreqdata ){
	  dbreq.setHeader('content-type', 'application/x-www-form-urlencoded');
	  dbreq.setHeader('content-length', dbreqdata.length);
	  dbreq.write(dbreqdata);
  }
  dbreq.end();
})

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});